(function ($) {
    $.fn.tableExport = function (options) {
    	 debugger
    	 var settings = $.extend({}, $.fn.tableExport.defaults, options),//由外部设置tableExport的默认参数
         rowD = $.fn.tableExport.rowDel;//分隔每行数据
    	 
    	 var $columns = this.bootstrapTable('getOptions').columns;
    	 
    	 $columns[0] = $columns[0].filter(function(item){
		        return item.field != "operate";
		 });
    	 var $columnsData={"field":[], 'title':[]};
    	 var $rowData=this.bootstrapTable('getData');
    	 $rowData.forEach(function(item){
    		 if(item.operate)
    			 delete item.operate;
    	 });
    	 debugger
    	 /**
          * 遍历所有的行数据，包括表头和表体
          */
         this.each(function () {
        	 //debugger
             var $el = $(this),//this指的就是这个table元素
                 //获取所有的行数据 包括表头、表体和表尾
                 $rows =  $el.find('tbody').find('tr'),
                 $rows = settings.headings ? $rows.add($el.find('thead>tr')) : $rows,//使用add方法
                 $rows = settings.footers ? $rows.add($el.find('tfoor>tr')) : $rows,

                 //设置导出文件的文件名
                 fileName = settings.fileName,
                 columnType=settings.columnType;
        		 //导出的各种类型
                 exporters = {
                     xlsx: function (rDel, name,columnType) {//xlsx类型---map方法的使用
                    	 //debugger
                    	 var dataURL=null;
                    	 if(columnType == "allColumns"){//导出所有的列
                    		 $columnsData.title = $columns[0].map(function (val) {
                        		 return val.title;
                        	 });
                        	 $columnsData.field = $columns[0].map(function (val) {
                        		 return val.field;
                        	 });
                        	 $rowData = $rowData.map(function (val){
                        		 return ($columnsData.field.map(function (field){
                        		     return val[field];
                        		 }));
                        	 });
                        	 dataURL=[$columnsData.title].concat($rowData);
                    	 }else if(columnType == "onlyShowColumns"){//导出table中显示的列
                    		 dataURL = $rows.map(function (i, val) {
                                 //该行数据所有的列
                                 var $cols = $(val).find('th, td');
                                 return [$cols.map(function (i, val) {
                                	 if($el.attr("id") == 'advQueryTable'){
                                		 if(i>0){
                                			 return $(val).text();
                                		 }
                                	 }else{
                                		 return $(val).text();
                                	 }
                                 }).get()];//["Rank", "Country", "Population", "% of world population", "Date"]
                             }).get();//[Array[5] ,Array[5],Array[5],Array[5],Array[5],Array[5],Array[5],Array[5],Array[5]
                    	 }
                         //debugger
                         //将dataObject绑定到元素上
                         $.fn.tableExport.xlsx.dataObject={
                    		 data: dataURL,
                             fileName: name,
                             mimeType: $.fn.tableExport.xlsx.mimeType,
                             fileExtension: $.fn.tableExport.xlsx.fileExtension
                         };
                         export2file($.fn.tableExport.xlsx.dataObject);
                     },
                     xls: function (rdel, name){//xls类型
                         //debugger
                         var colD = $.fn.tableExport.xls.separator,
                             dataURL = $rows.map(function (i, val) {
                                 var $cols = $(val).find('th, td');
                                 return $cols.map(function (i, val) {
                                	 if($el.attr("id") == 'advQueryTable'){
                                		 if(i>0){
                                			 return $(val).text();
                                		 }
                                	 }else{
                                		 return $(val).text();
                                	 }
                                 }).get().join(colD);
                             }).get().join(rdel);
                         	$.fn.tableExport.xls.dataObject={
                     			data: dataURL,
                                fileName: name,
                                mimeType: $.fn.tableExport.xls.mimeType,
                                fileExtension: $.fn.tableExport.xls.fileExtension
                         	};
                         	export2file($.fn.tableExport.xls.dataObject);
                     }
                 };
                 if(settings.type != ""){
                	 exporters[settings.type](rowD, fileName, columnType);
                 }
         });
    }
	//Define the plugin default properties.
	$.fn.tableExport.defaults = {
	      headings: true,
	      footers: true,
	      fileName: "myDownload",
	      type:"",
	      columnType:"onlyShowColumns"
	 };
	  $.fn.tableExport.charset = "charset=utf-8";
	  $.fn.tableExport.rowDel = "\r\n";
	  $.fn.tableExport.xlsx = {
	      mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
	      fileExtension: ".xlsx",
	      dataObject:null
	  };
	  $.fn.tableExport.xls = {
	      separator: "\t",
	      mimeType: "application/vnd.ms-excel",
	      fileExtension: ".xls",
	      dataObject:null
	  };
    /**
     * 导出绑定在按钮上的数据到文件当中去
     * @param dataObject
     */
    function export2file(dataObject) {
        if (dataObject.fileExtension === ".xlsx") {
            var wb = new Workbook(),
                ws = createSheet(dataObject.data);
            
            wb.SheetNames.push(dataObject.fileName);
            wb.Sheets[dataObject.fileName] = ws;

            var wopts = {bookType: 'xlsx', bookSST: false, type: 'binary'},
                wbout = XLSX.write(wb, wopts);

            dataObject.data = string2ArrayBuffer(wbout);
        }
        //debugger
        saveAs(new Blob([dataObject.data],
            {type: dataObject.mimeType + ";" + $.fn.tableExport.charset}),
            dataObject.fileName + dataObject.fileExtension);
    }
    function Workbook() {
        if (!(this instanceof Workbook)) return new Workbook();
        this.SheetNames = [];
        this.Sheets = {};
    }
    function createSheet(data, opts) {
        var ws = {};
        var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
        for (var R = 0; R != data.length; ++R) {
            for (var C = 0; C != data[R].length; ++C) {
                if (range.s.r > R) range.s.r = R;
                if (range.s.c > C) range.s.c = C;
                if (range.e.r < R) range.e.r = R;
                if (range.e.c < C) range.e.c = C;
                var cell = {v: data[R][C]};
                if (cell.v == null) continue;
                var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

                if (typeof cell.v === 'number') cell.t = 'n';
                else if (typeof cell.v === 'boolean') cell.t = 'b';
                else if (cell.v instanceof Date) {
                    cell.t = 'n';
                    cell.z = XLSX.SSF._table[14];
                    cell.v = dateNum(cell.v);
                }
                else cell.t = 's';
                ws[cell_ref] = cell;
            }
        }
        if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
        return ws;
    }
    function dateNum(v, date1904) {
        if (date1904) v += 1462;
        var epoch = Date.parse(v);
        return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
    }
    function string2ArrayBuffer(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
})(jQuery);